package org.darkforest.admin.controller;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.darkforest.admin.service.AdminLogService;
import org.darkforest.annotation.ArchivesLog;
import org.darkforest.annotation.ControllerLog;
import org.darkforest.common.constant.Constants;
import org.darkforest.common.mail.MailUtil;
import org.darkforest.common.services.*;
import org.darkforest.common.util.AliOssFileUploadUtil;
import org.darkforest.common.util.BeanUtils;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.SystemConstant;
import org.darkforest.common.util.Utils;
import org.darkforest.controller.WebController;
import org.darkforest.dao.mapper.*;
import org.darkforest.dao.redis.GoodsClassRedisDao;
import org.darkforest.dao.redis.GoodsRedisDao;
import org.darkforest.dao.redis.PBoothGoodsRedisDao;
import org.darkforest.enums.SettingNameEnum;
import org.darkforest.model.*;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.vo.MemberBase;
import org.darkforest.vo.SiteSettingInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by valentina on 15/5/10.
 * 主菜单：设置中相关操作类
 */
@Controller
@RequestMapping("setting")
public class SettingController extends WebController<SettingController> {

    @Autowired
    private MemberMsgTplMapper memberMsgTplMapper;

    @Autowired
    private SettingService settingService;

    @Autowired
    private AdminLogService adminLogService;

    @Autowired
    private ExpressService expressService;

    @Autowired
    private WaybillService waybillService;

    @Autowired
    private DeliverService deliverService;

    @Autowired
    private GoodsClassMapper goodsClassMapper;

    @Autowired
    private GoodsClassRedisDao goodsClassRedisDao;

    @Autowired
    private SettingMapper settingMapper;

    @Autowired
    private SimpleRedisService redisService;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsRedisDao goodsRedisDao;

    @Autowired
    private GoodsClassRedisService goodsClassRedisService;

    @Autowired
    private AdvSerivce advSerivce;
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private GAdminMapper gAdminMapper;

    @Autowired
    private MenusMapper menusMapper;

    @Autowired
    private SeoMapper seoMapper;

    @Autowired
    private PBoothGoodsMapper pBoothGoodsMapper;

    @Autowired
    private PBoothGoodsRedisDao pBoothGoodsRedisDao;

    @Autowired
    private FestivalMapper festivalMapper;
    @Autowired
    private FestivalService festivalService;

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private EnumParamMapper enumParamMapper;

    @Autowired
    private HealthDeptMapper healthDeptMapper;


    Logger logger = LoggerFactory.getLogger(SettingController.class);


    /**
     * 设置seo
     *
     * @return
     */
    @RequestMapping("seoset")
    public ModelAndView seoset() {
        ModelAndView modelAndView = new ModelAndView("setting/seo");
        try {
            Seo seo = new Seo();
            seo.setPageSwitch(false);
            modelAndView.addObject("seoList", seoMapper.selectByCondition(seo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }


    /**
     * seo更新
     * @return
     */
    @ControllerLog(description = "seo更新")
    @RequestMapping("seosetupdate")
    public ModelAndView seosetupdate(Seo seo) {
        ModelAndView modelAndView = new ModelAndView("redirect:/setting/seoset");
        seoMapper.updateByPrimaryKeySelective(seo);
        return modelAndView;
    }

    /**
     * 设置站点首页
     *
     * @return
     */
    @RequestMapping("uploadset")
    public ModelAndView uploadSet() {
        ModelAndView modelAndView = new ModelAndView("setting/upload");
        try {
            modelAndView.addObject("image_max_filesize_value",settingService.getSettingInfo(SettingNameEnum.IMAGE_MAX_FILESIZE));
            modelAndView.addObject("image_allow_ext_value",settingService.getSettingInfo(SettingNameEnum.IMAGE_ALLOW_EXT));
            modelAndView.addObject("default_goods_image_value",settingService.getSettingInfo(SettingNameEnum.DEFAULT_GOODS_IMAGE));
            modelAndView.addObject("default_store_logo_value",settingService.getSettingInfo(SettingNameEnum.DEFAULT_STORE_LOGO));
            modelAndView.addObject("default_store_avatar_value",settingService.getSettingInfo(SettingNameEnum.DEFAULT_STORE_AVATAR));
            modelAndView.addObject("default_user_portrait_value",settingService.getSettingInfo(SettingNameEnum.DEFAULT_USER_PORTRAIT));
            modelAndView.addObject("login_pic1_value",settingService.getSettingInfo(SettingNameEnum.LOGIN_PIC1));
            modelAndView.addObject("login_pic2_value",settingService.getSettingInfo(SettingNameEnum.LOGIN_PIC2));
            modelAndView.addObject("login_pic3_value",settingService.getSettingInfo(SettingNameEnum.LOGIN_PIC3));
            modelAndView.addObject("login_pic4_value",settingService.getSettingInfo(SettingNameEnum.LOGIN_PIC4));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 上传设置
     * @return
     */
    @ControllerLog(description = "上传设置更新")
    @RequestMapping("uploadsetupdate")
    public ModelAndView uploadsetupdate(MultipartHttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/setting/upload");
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String name = enums.nextElement();    //获取属性的名字
            String value = request.getParameter(name);
            MultipartFile multipartFile = request.getFile(name);
            if (multipartFile != null)
                if (multipartFile.getSize() > 0) {
                    String val = super.uploadPicsWithoutCompressSize(multipartFile, request, null, null);
                    updateSetting(name, val);
                }
            if (StringUtils.isNotEmpty(value) && value != "") {
                updateSetting(name, value);
            }
            modelAndView.addObject(name+"_value", settingService.getSettingInfo(SettingNameEnum.getSettingNameEnum(name)));
        }
        return modelAndView;
    }


    /**
     * 设置站点首页
     *
     * @return
     */
    @RequestMapping("site")
    public ModelAndView site() {
        ModelAndView modelAndView = new ModelAndView("setting/site");
        try {
            modelAndView.addObject("site_name_value", settingService.getSettingInfo(SettingNameEnum.SITE_NAME));
            modelAndView.addObject("site_logo_value", settingService.getSettingInfo(SettingNameEnum.SITE_LOGO));
            modelAndView.addObject("member_logo_value", settingService.getSettingInfo(SettingNameEnum.MEMBER_LOGO));
            modelAndView.addObject("seller_center_logo_value", settingService.getSettingInfo(SettingNameEnum.SELLER_CENTER_LOGO));
            modelAndView.addObject("icp_number_value", settingService.getSettingInfo(SettingNameEnum.ICP_NUMBER));
            modelAndView.addObject("site_phone_value", settingService.getSettingInfo(SettingNameEnum.SITE_PHONE));
            modelAndView.addObject("site_email_value", settingService.getSettingInfo(SettingNameEnum.SITE_EMAIL));
            modelAndView.addObject("statistics_code_value", settingService.getSettingInfo(SettingNameEnum.STATISTICS_CODE));
            modelAndView.addObject("time_zone_value", settingService.getSettingInfo(SettingNameEnum.TIME_ZONE));
            modelAndView.addObject("site_status_value",  settingService.getSettingInfo(SettingNameEnum.SITE_STATUS));
            modelAndView.addObject("site_search_value", settingService.getSettingInfo(SettingNameEnum.SITE_SEARCH));
            modelAndView.addObject("closed_reason_value", settingService.getSettingInfo(SettingNameEnum.CLOSED_REASON));
            modelAndView.addObject("domain_name_value", settingService.getSettingInfo(SettingNameEnum.DOMAIN_NAME));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }


    /**
     * 更新设置
     *
     * @param request
     * @return
     */
    @ControllerLog(description = "站点设置更新")
    @RequestMapping(value = "site/update", method = RequestMethod.POST)
    public ModelAndView siteUpdate(MultipartHttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("setting/site");
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String name = enums.nextElement();    //获取属性的名字
            String value = request.getParameter(name);
            MultipartFile multipartFile = request.getFile(name);
            if (multipartFile != null)
                if (multipartFile.getSize() > 0) {
                    String val = super.uploadPicsWithoutCompressSize(multipartFile, request, null, null);
                    updateSetting(name, val);
                }
            if (StringUtils.isNotEmpty(value) && value != "") {
                updateSetting(name, value);
                modelAndView.addObject(name+"_value", settingService.getSettingInfo(SettingNameEnum.getSettingNameEnum(name)));
            }
        }
        return modelAndView;
    }


    /**
     * 更新设置
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "qqaccount/update", method = RequestMethod.POST)
    public ModelAndView qqaccountUpdate(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("setting/account/qqaccount");
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String name = enums.nextElement();    //获取属性的名字
            String value = request.getParameter(name);
            if (StringUtils.isNotEmpty(value) && value != "") {
                updateSetting(name, value);
            }
        }
        modelAndView.addObject("qq_isuse_value", settingService.getSettingInfo(SettingNameEnum.QQ_ISUSE));
        modelAndView.addObject("qq_appcode_value", settingService.getSettingInfo(SettingNameEnum.QQ_APPCODE));
        modelAndView.addObject("qq_appid_value", settingService.getSettingInfo(SettingNameEnum.QQ_APPID));
        modelAndView.addObject("qq_appkey_value", settingService.getSettingInfo(SettingNameEnum.QQ_APPKEY));
        return modelAndView;
    }

    /**
     * 邮件设置显示
     *
     * @return
     */
    @RequestMapping("account")
    public ModelAndView account() {
        ModelAndView modelAndView = new ModelAndView("setting/account/qqaccount");
        try {
            modelAndView.addObject("qq_isuse_value", settingService.getSettingInfo(SettingNameEnum.QQ_ISUSE));
            modelAndView.addObject("qq_appcode_value", settingService.getSettingInfo(SettingNameEnum.QQ_APPCODE));
            modelAndView.addObject("qq_appid_value", settingService.getSettingInfo(SettingNameEnum.QQ_APPID));
            modelAndView.addObject("qq_appkey_value", settingService.getSettingInfo(SettingNameEnum.QQ_APPKEY));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 设置参数更新方法
     * @param name
     * @param value
     * @return
     */
    private Integer updateSetting(String name, String value) {
        Setting set = new Setting();
        set.setName(name);
        set.setValue(value);
        return  settingService.updateSetting(set);
    }

    /**
     * 邮件设置显示
     *
     * @return
     */
    @RequestMapping("message")
    public ModelAndView emailEessage() {
        ModelAndView modelAndView = new ModelAndView("setting/message/email");
        try {
            modelAndView.addObject("email_host_value", settingService.getSettingInfo(SettingNameEnum.EMAIL_HOST));
            modelAndView.addObject("email_port_value", settingService.getSettingInfo(SettingNameEnum.EMAIL_PORT));
            modelAndView.addObject("email_addr_value", settingService.getSettingInfo(SettingNameEnum.EMAIL_ADDR));
            modelAndView.addObject("email_id_value", settingService.getSettingInfo(SettingNameEnum.EMAIL_ID));
            modelAndView.addObject("email_pass_value", settingService.getSettingInfo(SettingNameEnum.EMAIL_PASS));
            modelAndView.addObject("email_test_value", settingService.getSettingInfo(SettingNameEnum.EMAIL_TEST));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /**
     * 邮件设置更新
     *
     * @param request
     * @return
     */

    @RequestMapping("message/email/update")
    public ModelAndView emailUpdate(HttpServletRequest request) {
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String name = enums.nextElement();    //获取属性的名字
            String value = request.getParameter(name);
            if (StringUtils.isNotEmpty(value) && value != "") {
                updateSetting(name, value);
            }
        }

        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", "邮件设置修改成功");
        modelAndView.addObject("returnUrl", "setting/message");
        return modelAndView;
    }

    /**
     * 测试发送邮件
     * @param email
     * @return
     */
    @RequestMapping(value = "message/email/testSendEmail")
    @ResponseBody
    public String testSendEmail(String sender,String email){
        MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("test_send_email");
        if ("465".equals(SystemConstant.PORT.trim())) {
            String retVal = MailUtil.sendMailBySSL(memberMsgTpl.getMmtMailSubject(), memberMsgTpl.getMmtMailContent(), sender, email);
            return retVal;
        } else {
            // 25
            MailUtil.sendMail(memberMsgTpl.getMmtMailSubject(), memberMsgTpl.getMmtMailContent(), sender, email);
        }
        return "success";
    }

    /**
     * 查询支付方式的状态
     *
     * @return
     */
    @RequestMapping("systempayment")
    public ModelAndView payment() {
        ModelAndView modelAndView = new ModelAndView("/setting/pay/payment");
        modelAndView.addObject("alipay_state_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_STATE));
        modelAndView.addObject("alipay_bank_state_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_STATE));
        modelAndView.addObject("wechatpay_state_value", settingService.getSettingInfo(SettingNameEnum.WECHATPAY_STATE));
        return modelAndView;
    }

    /**
     * 支付宝-实时到帐
     * @return
     */
    @RequestMapping("alipay")
    public ModelAndView alipay() {
        ModelAndView modelAndView = new ModelAndView("/setting/pay/alipay");
        modelAndView.addObject("alipay_state_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_STATE));
        modelAndView.addObject("alipay_account_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_ACCOUNT));
        modelAndView.addObject("alipay_key_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_KEY));
        modelAndView.addObject("alipay_partner_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_PARTNER));
        return modelAndView;
    }

    /**
     * 支付宝-实时到帐更新
     * @return
     */
    @RequestMapping("alipayupdate")
    public ModelAndView alipayUpadte(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/setting/pay/alipay");
        String alipay_state = request.getParameter("alipay_state");
        String alipay_account = request.getParameter("alipay_account");
        String alipay_key  = request.getParameter("alipay_key");
        String alipay_partner = request.getParameter("alipay_partner");
        if(Utils.isNotEmpty(alipay_state)){
            updateSetting("alipay_state",alipay_state);
        }
        if(Utils.isNotEmpty(alipay_account)){
            updateSetting("alipay_account",alipay_account);
        }
        if(Utils.isNotEmpty(alipay_state)){
            updateSetting("alipay_state",alipay_state);
        }
        if(Utils.isNotEmpty(alipay_key)){
            updateSetting("alipay_key",alipay_key);
        }
        if(Utils.isNotEmpty(alipay_partner)){
            updateSetting("alipay_partner",alipay_partner);
        }

        modelAndView.addObject("alipay_state_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_STATE));
        modelAndView.addObject("alipay_account_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_ACCOUNT));
        modelAndView.addObject("alipay_key_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_KEY));
        modelAndView.addObject("alipay_partner_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_PARTNER));
        return modelAndView;
    }

    /**
     * 支付宝-网银支付
     * @return
     */
    @RequestMapping("alipaybank")
    public ModelAndView alipaybank() {
        ModelAndView modelAndView = new ModelAndView("/setting/pay/alipaybank");
        modelAndView.addObject("alipay_bank_state_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_STATE));
        modelAndView.addObject("alipay_bank_account_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_ACCOUNT));
        modelAndView.addObject("alipay_bank_key_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_KEY));
        modelAndView.addObject("alipay_bank_partner_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_PARTNER));
        return modelAndView;
    }

    /**
     * 支付宝-网银支付更新
     * @param request
     * @return
     */
    @RequestMapping("alipaybankupdate")
    public ModelAndView alipayBankUpadte(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/setting/pay/alipaybank");
        String alipay_bank_state = request.getParameter("alipay_bank_state");
        String alipay_bank_account = request.getParameter("alipay_bank_account");
        String alipay_bank_key  = request.getParameter("alipay_bank_key");
        String alipay_bank_partner = request.getParameter("alipay_bank_partner");
        if(Utils.isNotEmpty(alipay_bank_state)){
            updateSetting("alipay_bank_state",alipay_bank_state);
        }
        if(Utils.isNotEmpty(alipay_bank_account)){
            updateSetting("alipay_bank_account",alipay_bank_account);
        }
        if(Utils.isNotEmpty(alipay_bank_state)){
            updateSetting("alipay_bank_state",alipay_bank_state);
        }
        if(Utils.isNotEmpty(alipay_bank_key)){
            updateSetting("alipay_bank_key",alipay_bank_key);
        }
        if(Utils.isNotEmpty(alipay_bank_partner)){
            updateSetting("alipay_bank_partner",alipay_bank_partner);
        }

        modelAndView.addObject("alipay_bank_state_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_STATE));
        modelAndView.addObject("alipay_bank_account_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_ACCOUNT));
        modelAndView.addObject("alipay_bank_key_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_KEY));
        modelAndView.addObject("alipay_bank_partner_value", settingService.getSettingInfo(SettingNameEnum.ALIPAY_BANK_PARTNER));
        return modelAndView;
    }

    /**
     * 获取微信支付参数
     * @return
     */

    @RequestMapping("wechatpay")
    public ModelAndView wechatpay() {
        ModelAndView modelAndView = new ModelAndView("/setting/pay/wechatpay");
        modelAndView.addObject("wechatpay_state_value", settingService.getSettingInfo(SettingNameEnum.WECHATPAY_STATE));
        modelAndView.addObject("wxpay_app_id_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_APP_ID));
        modelAndView.addObject("wxpay_app_secret_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_APP_SECRET));
        modelAndView.addObject("wxpay_token_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_TOKEN));
        modelAndView.addObject("wxpay_partner_key_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_PARTNER_KEY));
        modelAndView.addObject("wxpay_mcht_id_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_MCHT_ID));
        modelAndView.addObject("wxpay_spbill_create_ip_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_SPBILL_CREATE_IP));
        modelAndView.addObject("wxpay_sign_type_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_SIGN_TYPE));
        modelAndView.addObject("wxpay_notify_url_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_NOTIFY_URL));
        modelAndView.addObject("wxpay_trade_type_js_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_TRADE_TYPE_JS));
        modelAndView.addObject("wxpay_input_charset_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_INPUT_CHARSET));
        modelAndView.addObject("wxpay_refund_url_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_REFUND_URL));
        modelAndView.addObject("wxpay_pay_interface_value", settingService.getSettingInfo(SettingNameEnum.WXPAY_PAY_INTERFACE));
        modelAndView.addObject("wx_corp_id", settingService.getSettingInfo(SettingNameEnum.WXCORPID));
        modelAndView.addObject("wx_corp_secret", settingService.getSettingInfo(SettingNameEnum.WXCORPSECRET));
        return modelAndView;
    }

    /**
     * 微信支付更新
     * @return
     */
    @RequestMapping("wechatpayupdate")
    public ModelAndView wechatpayUpdate(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/setting/pay/wechatpay");
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String name = enums.nextElement();    //获取属性的名字
            String value = request.getParameter(name);
            if (StringUtils.isNotEmpty(value) && value != "") {
                updateSetting(name, value);
            }
            modelAndView.addObject(name+"_value", settingService.getSettingInfo(SettingNameEnum.getSettingNameEnum(name)));
        }
        return modelAndView;
    }

    /**
     * 用户消息模板列表
     *
     * @return
     */
    @RequestMapping("message/userMsgTplList")
    public ModelAndView userMsgTpl(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("setting/message/user_msg_templet");
        MemberMsgTpl memberMsgTpl = new MemberMsgTpl();
        if (StringUtils.isEmpty(request.getParameter("mmtType"))) {
            memberMsgTpl.setMmtType("member");
        } else {
            memberMsgTpl.setMmtType(request.getParameter("mmtType"));
        }
        // 改页处理用
        String start = request.getParameter("start");
        if (start != null && !"".equals(start)) {
            memberMsgTpl.setStart(Integer.valueOf(start));
        }
        List<MemberMsgTpl> memberMsgTplList = memberMsgTplMapper.findMemberMsgTplByConditon(memberMsgTpl);
//        modelAndView.addObject("memberMsgTplList", memberMsgTplList);
        memberMsgTpl.setResultList(memberMsgTplList);
        modelAndView.addObject("page", memberMsgTpl);
//        modelAndView.addObject("mmtType", mmtType);
        return modelAndView;
    }

    /**
     * 用户消息模板编辑页面
     *
     * @return
     */
    @RequestMapping("message/toUserMsgTplEdit")
    public ModelAndView toUserMsgTplEdit(String mmtCode) {
        ModelAndView modelAndView = new ModelAndView("setting/message/user_msg_templet_edit");
        MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey(mmtCode);
        modelAndView.addObject("memberMsgTpl", memberMsgTpl);

        // 订单接受人员手机号
        if ("order_payment_success".equals(mmtCode)) {
            modelAndView.addObject("mobilePhone", settingService.getSettingInfo(SettingNameEnum.OPERATION_MOBILE_PHONE));
        }
        // 体检管理员邮件地址
        if ("health_send_email".equals(mmtCode)) {
            modelAndView.addObject("mailAddress", settingService.getSettingInfo(SettingNameEnum.OPERATION_MAIL_ADDRESS));
        }
        return modelAndView;
    }

    /**
     * 用户消息模板编辑保存
     *
     * @return
     */
    @RequestMapping("message/doUserMsgTplEdit")
    public ModelAndView doUserMsgTplEdit(MemberMsgTpl memberMsgTpl, HttpServletRequest request) {
        int i = memberMsgTplMapper.updateByPrimaryKeySelective(memberMsgTpl);
        // 订单接受人员手机号
        if ("order_payment_success".equals(memberMsgTpl.getMmtCode())) {
            String name = "operation_mobile_phone";
            String value = request.getParameter(name);
            if (StringUtils.isNotEmpty(value)) {
                updateSetting(name, value);
            }
        }

        ModelAndView modelAndView = new ModelAndView("msg");
        if (i > 0) {
            modelAndView.addObject("msg", "消息模板修改成功");
        } else {
            modelAndView.addObject("msg", "消息模板修改失败");
        }
        modelAndView.addObject("returnUrl", "setting/message/userMsgTplList?mmtType="+memberMsgTpl.getMmtType());
        return modelAndView;
    }

    /**
     * 结算设置
     * @return
     */
    @RequestMapping("settlement")
    public ModelAndView setSettlement(){
        ModelAndView modelAndView = new ModelAndView("setting/settlement");
        try {
            modelAndView.addObject("settlement_register_integration_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_REGISTER_INTEGRATION));
            modelAndView.addObject("settlement_recommend_integration_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_RECOMMEND_INTEGRATION));
            modelAndView.addObject("settlement_consume_integration_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_CONSUME_INTEGRATION));
            modelAndView.addObject("settlement_altogether_integration_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_ALTOGETHER_INTEGRATION));
            modelAndView.addObject("settlement_level3_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_LEVEL3));
            modelAndView.addObject("settlement_level2_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_LEVEL2));
            modelAndView.addObject("settlement_level1_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_LEVEL1));
            modelAndView.addObject("settlement_return_integration_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_RETURN_INTEGRATION));
            modelAndView.addObject("settlement_subsidy_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_SUBSIDY));
            modelAndView.addObject("settlement_subsidy_time_value",settingService.getSettingInfo(SettingNameEnum.SETTLEMENT_SUBSIDY_TIME));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;

    }



    /**
     * 结算设置更新
     * @returnU
     */
    @RequestMapping("settlementupdate")
    public ModelAndView settlementUpdate(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("setting/settlement");
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String name = enums.nextElement();    //获取属性的名字
            String value = request.getParameter(name);
            if (StringUtils.isNotEmpty(value) && value != "") {
                updateSetting(name, value);
            }
            modelAndView.addObject(name+"_value", settingService.getSettingInfo(SettingNameEnum.getSettingNameEnum(name)));
        }
        return modelAndView;
    }

    /**
     * 运营基本设置
     *
     * @return
     */
    @RequestMapping("settingoperation")
    public ModelAndView operationset() {
        ModelAndView modelAndView = new ModelAndView("setting/operation");
        modelAndView.addObject("operation_promotion_allow_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_PROMOTION_ALLOW));
        modelAndView.addObject("operation_groupbuy_allow_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_GROUPBUY_ALLOW));
        modelAndView.addObject("operation_points_isuse_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_POINTS_ISUSE));
        modelAndView.addObject("operation_pointshop_isuse_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_POINTSHOP_ISUSE));
        modelAndView.addObject("operation_pointprod_isuse_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_POINTPROD_ISUSE));
        modelAndView.addObject("operation_voucher_allow_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_VOUCHER_ALLOW));
        modelAndView.addObject("operation_points_reg_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_POINTS_REG));
        modelAndView.addObject("operation_points_login_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_POINTS_LOGIN));
        modelAndView.addObject("operation_points_comments_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_POINTS_COMMENTS));
        modelAndView.addObject("operation_points_orderrate_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_POINTS_ORDERRATE));
        modelAndView.addObject("operation_points_ordermax_value", settingService.getSettingInfo(SettingNameEnum.OPERATION_POINTS_ORDERMAX));
        return modelAndView;
    }

    /**
     * 运营基本设置
     * @returnU
     */
    @RequestMapping("operationsetupdate")
    public ModelAndView operationsetupdate(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("setting/operation");
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String name = enums.nextElement();    //获取属性的名字
            String value = request.getParameter(name);
            if (StringUtils.isNotEmpty(value) && value != "") {
                updateSetting("operation_" + name, value);
            }
            modelAndView.addObject("operation_" + name+"_value", settingService.getSettingInfo(SettingNameEnum.getSettingNameEnum("operation_" + name)));
        }
        return modelAndView;
    }

    /**
     * 缓存
     * @return
     */
    @RequestMapping("cache")
    public String cache() {
        return "setting/cache";
    }
    /**
     * 更新缓存
     * @return
     */
    @RequestMapping("cache/cacheupdate")
    public ModelAndView cacheupdate(HttpServletRequest request) {
        String cache[] = request.getParameterValues("cache");
        if(cache!=null) {
            for (String name : cache) {
                //商城配置
                if (name.equals("setting")) {
                    List<Setting> settings = settingService.findAllSetting();
                    for (Setting setting : settings) {
                        redisService.setValue(setting.getName(), setting.getValue());
                    }

                    //读取数据库配置加载到对象
                    SiteSettingInfo siteSettingInfo = new SiteSettingInfo();
                    settingService.initSiteSetting(siteSettingInfo);
                }
                //商品分类
                if(name.equals("goodsclass")){
                    GoodsClass goodsClassParam = new GoodsClass();
                    goodsClassParam.setGcParentId(0);
                    goodsClassParam.setPageSwitch(false);
                    List<GoodsClass> parentClass = goodsClassMapper.findGoodsClass(goodsClassParam);
                    if (parentClass != null) {
                        goodsClassRedisDao.deleteList("gc_list");
                        goodsClassRedisDao.addClassList("gc_list", parentClass);
                        logger.debug("----add gc_list----");
                        for (GoodsClass cls : parentClass) {
                            logger.debug("----gc_list:" + cls.getGcId() + ",name:" + cls.getGcName() + "-----");
                            goodsClassParam.setGcParentId(cls.getGcId());
                            List<GoodsClass> level2Class = goodsClassMapper.findGoodsClass(goodsClassParam);
                            if (level2Class != null) {
                                goodsClassRedisDao.deleteList("gc_list_" + cls.getGcId());
                                goodsClassRedisDao.addClassList("gc_list_" + cls.getGcId(), level2Class);
                                for (GoodsClass subCls : level2Class) {
                                    logger.debug("----sub gc_list:" + subCls.getGcId() + ",sub cls name:" + subCls.getGcName() + "-----");
                                    goodsClassParam.setGcParentId(subCls.getGcId());
                                    List<GoodsClass> level3Class = goodsClassMapper.findGoodsClass(goodsClassParam);
                                    if (level3Class != null) {
                                        goodsClassRedisDao.deleteList("gc_list_" + subCls.getGcId());
                                        goodsClassRedisDao.addClassList("gc_list_" + subCls.getGcId(), level3Class);
                                    }
                                }
                            }
                        }
                    }
                }
                if(name.equals("adv")){
                    AdvBean adv = new AdvBean();
                    adv.setIsUse((byte)1);
                    adv.setPageSwitch(false);
                    List<Adv> list = advSerivce.selectByCondition(adv);
                    for(Adv ad:list){
                        advSerivce.deleteRedisAdvList("adv_"+ad.getApId());
                    }
                }
//                //首页
//                if(name.equals("index")){
//                    Goods param = new Goods();
//                    param.setRecommondType(1);
//                    param.setLimit(8);
//                    GoodsClass goodsClassParam = new GoodsClass();
//                    goodsClassParam.setGcParentId(0);
//                    goodsClassParam.setPageSwitch(false);
//                    List<GoodsClass> clsList = goodsClassMapper.findGoodsClass(goodsClassParam);
//                    for(GoodsClass cls:clsList){
//                        param.setGcId1(cls.getGcId());
//                        List<Goods> goodsList = goodsMapper.findRecommendGoodsByCond(param);
//                        //写入redis
//                        goodsRedisDao.addGoodsList("goods_list_"+cls.getGcId(),goodsList);
//                    }
//
//
//                    List<GoodsClass> gcs=pBoothGoodsMapper.selectGoodsClassIds();
//                    goodsClassRedisDao.deleteList("gc_list_index");
//                    goodsClassRedisDao.addClassList("gc_list_index",gcs);
//                    PBoothGoods pBoothGoods = new PBoothGoods();
//                    pBoothGoods.setPageSize(6);
//                    pBoothGoods.setStart(1);
//                    pBoothGoods.setBoothState((byte)1);
//                    for(GoodsClass gc:gcs){
//                        pBoothGoods.setGcId(gc.getGcId());
//                        pBoothGoods.setRecommondType(1);
//                        List<PBoothGoods> pbgs1= pBoothGoodsMapper.selectRecommondGoodsByPage(pBoothGoods);
//                        pBoothGoodsRedisDao.deleteList("goods_index_1_"+gc.getGcId());
//                        pBoothGoodsRedisDao.addPBoothGoodsList("goods_index_1_" + gc.getGcId(),pbgs1);
//
//                        pBoothGoods.setRecommondType(2);
//                        List<PBoothGoods> pbgs2= pBoothGoodsMapper.selectRecommondGoodsByPage(pBoothGoods);
//                        pBoothGoodsRedisDao.deleteList("goods_index_2_"+gc.getGcId());
//                        pBoothGoodsRedisDao.addPBoothGoodsList("goods_index_2_" + gc.getGcId(),pbgs2);
//
//                        pBoothGoods.setRecommondType(3);
//                        List<PBoothGoods> pbgs3= pBoothGoodsMapper.selectRecommondGoodsByPage(pBoothGoods);
//                        pBoothGoodsRedisDao.deleteList("goods_index_3_"+gc.getGcId());
//                        pBoothGoodsRedisDao.addPBoothGoodsList("goods_index_3_" + gc.getGcId(),pbgs3);
//
//                        advSerivce.deleteRedisAdvList("adv_index_"+gc.getGcId());
//                    }
//                    advSerivce.deleteRedisAdvList("adv_index_"+0);
//
//
//                }
            }
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("returnUrl","setting/cache");
        return modelAndView;
    }

    /**
     * 日志
     * @return
     */
    @RequestMapping("adminlog")
    public ModelAndView adminlog(AdminLog page){
        ModelAndView modelAndView = new ModelAndView("setting/adminlog");
        adminLogService.selectListByCondition(page);
        modelAndView.addObject("page",page);
        return modelAndView;
    }

    /**
     * 快递公司
     * @return
     */
    @RequestMapping("express")
    public ModelAndView express(Express page){
        ModelAndView modelAndView = new ModelAndView("setting/express");
        expressService.selectByCondition(page);
        modelAndView.addObject("eLetter",page.geteLetter());
        modelAndView.addObject("page",page);
        return modelAndView;
    }

    @RequestMapping("editeState")
    public ModelAndView editeState(int id,String eState,String eLetter){
        ModelAndView modelAndView = new ModelAndView("redirect:/setting/express?eLetter="+eLetter);
        Express page = expressService.selectByPrimaryKey(id);
        page.seteState(eState);
        expressService.updateByPrimaryKeySelective(page);
        return modelAndView;
    }
    @RequestMapping("editeOrder")
    public ModelAndView editeOrder(int id,String eOrder,String eLetter){
        ModelAndView modelAndView = new ModelAndView("redirect:/setting/express?eLetter="+eLetter);
        Express page = expressService.selectByPrimaryKey(id);
        page.seteOrder(eOrder);
        expressService.updateByPrimaryKeySelective(page);
        return modelAndView;
    }

    /**
     * 运费模版
     * @return
     */
    @RequestMapping("waybill")
    public ModelAndView waybill(Waybill page){
        ModelAndView modelAndView = new ModelAndView("setting/waybill/waybill");
        waybillService.selectByCondition(page);
        modelAndView.addObject("page",page);
        return modelAndView;
    }

    /**
     * 运费模版
     * @return
     */
    @RequestMapping("waybill/waybillAdd")
    public ModelAndView waybillAdd(){
        List companyList = deliverService.selectAllExpress();
        return new ModelAndView("setting/waybill/waybillAdd", "companyList", companyList);
    }

    /**
     * 运费模版
     * @return
     */
    @RequestMapping("waybill/waybilldesign")
    public ModelAndView waybilldesign(Waybill page){
        ModelAndView modelAndView = new ModelAndView("setting/waybill/waybilldesign");
        Waybill bill = waybillService.selectByPrimaryKey(page.getWaybillId());
        String data = bill.getWaybillData();
        if(data!=null&&!"".equals(data)){
            JSONObject jsonObject =  JSONObject.fromObject(data);
            WayBillData  billData = (WayBillData) JSONObject.toBean(jsonObject, WayBillData.class);
            bill.setBillData(billData);
        }
        modelAndView.addObject("bill",bill);
        return modelAndView;
    }

    /**
     * 运费模版
     * @return
     */
    @RequestMapping("test")
    public ModelAndView test(Waybill page){
        ModelAndView modelAndView = new ModelAndView("setting/waybill/test");
        Waybill bill = waybillService.selectByPrimaryKey(page.getWaybillId());
        String data = bill.getWaybillData();
        if(data!=null&&!"".equals(data)){
            JSONObject jsonObject =  JSONObject.fromObject(data);
            WayBillData  billData = (WayBillData) JSONObject.toBean(jsonObject, WayBillData.class);
            bill.setBillData(billData);
        }
        modelAndView.addObject("bill",bill);
        return modelAndView;
    }


    /**
     * 添加运费模版
     * @return
     */
    @RequestMapping("waybill/waybillAdddo")
    public ModelAndView waybillAdddo(Waybill waybill, MultipartFile waybillImage1) {
        if(waybillImage1!=null){
            String oldName = waybillImage1.getOriginalFilename();
            if(oldName!=null&&!"".equals(oldName)) {
                int extIndex = waybillImage1.getOriginalFilename().lastIndexOf(".");
                String extName =  "";
                if (extIndex > 0) {
                    extName =  waybillImage1.getOriginalFilename().substring(extIndex);
                }
                String name = new Date().getTime()  + extName;
                String begin = System.getProperty("user.dir");
                File targetFile = new File(begin, name);
                try {
                    waybillImage1.transferTo(targetFile);
                    AliOssFileUploadUtil.uploadPic(new Date().getTime() + "", name, targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    ModelAndView modelAndView = new ModelAndView("msg");
                    modelAndView.addObject("msg", "运费模版保存失败!");
                    modelAndView.addObject("returnUrl", "setting/waybill");
                    return modelAndView;
                }
                waybill.setWaybillImage(name);
            }
        }
        waybill.setStoreId(0);
        waybillService.insert(waybill);

        ModelAndView modelAndView = new ModelAndView("redirect:/setting/waybill");
        return modelAndView;
    }
    /**
     * 编辑运费模版
     * @return
     */
    @RequestMapping("waybill/waybillEdit")
    public ModelAndView waybillEdit(Waybill page){
        List companyList = deliverService.selectAllExpress();
        ModelAndView modelAndView = new ModelAndView("setting/waybill/waybillEdit");
        modelAndView.addObject("waybill",waybillService.selectByPrimaryKey(page.getWaybillId()));
        modelAndView.addObject("companyList", companyList);
        return modelAndView;
    }

    /**
     * 删除运费模版
     * @return
     */
    @RequestMapping("waybill/waybillDel")
    public ModelAndView waybillDel(Waybill page){
        ModelAndView modelAndView = new ModelAndView("redirect:/setting/waybill");
        waybillService.deleteByPrimaryKey(page.getWaybillId());
        return modelAndView;
    }


    /**
     * 编辑运费模版
     * @return
     */
    @RequestMapping("waybill/waybillEditdo")
    public ModelAndView waybillEditdo(Waybill waybill, MultipartFile waybillImage1) {
        if(waybillImage1!=null){
            String oldName = waybillImage1.getOriginalFilename();
            if(oldName!=null&&!"".equals(oldName)) {
                int extIndex = waybillImage1.getOriginalFilename().lastIndexOf(".");
                String extName =  "";
                if (extIndex > 0) {
                    extName =  waybillImage1.getOriginalFilename().substring(extIndex);
                }
                String name = new Date().getTime() + extName;
                String begin = System.getProperty("user.dir");
                File targetFile = new File(begin, name);
                try {
                    waybillImage1.transferTo(targetFile);
                    AliOssFileUploadUtil.uploadPic(new Date().getTime() + "", name, targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    ModelAndView modelAndView = new ModelAndView("msg");
                    modelAndView.addObject("msg", "运费模版保存失败!");
                    modelAndView.addObject("returnUrl", "setting/waybill");
                    return modelAndView;
                }
                waybill.setWaybillImage(name);
            }
        }
        ModelAndView modelAndView = new ModelAndView("redirect:/setting/waybill");
        waybillService.updateByPrimaryKeySelective(waybill);
        modelAndView.addObject("page",waybill);
        return modelAndView;
    }

    /**
     * 编辑运费模版
     * @return
     */
    @RequestMapping(value = "waybill/saveDesign")
    public ModelAndView saveDesign(Waybill waybill,WayBillData billData) {
        String data  = JSON.toJSONString(billData);
        waybill.setWaybillData(data);
        waybillService.updateByPrimaryKeySelective(waybill);
        return new ModelAndView("redirect:/setting/waybill");
    }

    /**
     * 权限管理
     * @param request
     * @return
     */
    @RequestMapping("permission")
    @AuthPassport
    public ModelAndView permissionList(HttpServletRequest request) {
        Admin admin = new Admin();
        // 改页处理用
        String start = request.getParameter("start");
        if (start != null && !"".equals(start)) {
            admin.setStart(Integer.valueOf(start));
        }
        admin.setResultList(adminMapper.selectByCondition(admin));
        ModelAndView view = new ModelAndView("setting/permission/permissionList");
        view.addObject("page",admin);
        return view;
    }

    /**
     * 管理员添加
     * @return
     */
    @RequestMapping("permission/adminToAdd")
    public ModelAndView adminToAdd() {

        ModelAndView mv = new ModelAndView("setting/permission/adminadd");

        List<GAdmin> gAdminList = gAdminMapper.selectByCondition(new GAdmin());
        mv.addObject("gAdminList",gAdminList);

        // 体检人员部门的取得
        HealthDept healthDeptment = new HealthDept();
        healthDeptment.setPageSwitch(false);
        List<HealthDept> healthDeptmentList = healthDeptMapper.selectListByCondition(healthDeptment);
        mv.addObject("healthDeptList", healthDeptmentList);

        return mv;
    }

    @RequestMapping("permission/adminDoAdd")
    @ArchivesLog(operationDescription = "新增管理员")
    public ModelAndView adminDoAdd(HttpServletRequest request) {

        Admin admin = new Admin();
        admin.setAdminName(request.getParameter("adminName"));
        String adminPassword = request.getParameter("adminPassword");
        if (StringUtils.isNotEmpty(adminPassword)) {
            admin.setAdminPassword(DigestUtils.md5Hex(adminPassword));
        }
        // 权限组
        String adminGid = request.getParameter("adminGid");
        admin.setAdminGid(Short.valueOf(adminGid));

        // 体检部门ID
        String healthDeptId = request.getParameter("healthDeptId");
        if (StringUtils.isNotEmpty(healthDeptId)) {
            admin.setHealthDeptId(Integer.valueOf(request.getParameter("healthDeptId")));
        }

        admin.setAdminLoginTime(0);
        admin.setAdminLoginNum(0);
        admin.setAdminIsSuper(false);

        int i = adminMapper.insert(admin);
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i > 0) {
            modelAndView.addObject("msg", "管理员新增成功");
        } else {
            modelAndView.addObject("msg", "管理员新增失败");
        }
        modelAndView.addObject("returnUrl", "setting/permission");
        return modelAndView;
    }

    /**
     *  管理员修改
     * @param adminId
     * @return
     */
    @RequestMapping("permission/adminToEdit")
    public ModelAndView adminToEdit(Integer adminId) {
        ModelAndView mv = new ModelAndView("setting/permission/adminedit");

        // 选择的用户信息显示用
        Admin adminInfo = adminMapper.selectByPrimaryKey(adminId);
        mv.addObject("adminInfo", adminInfo);

        // 取得所有权限（下拉列表用）
        List<GAdmin> gAdminList = gAdminMapper.selectByCondition(new GAdmin());
        mv.addObject("gAdminList",gAdminList);

        // 体检人员部门的取得
        HealthDept healthDeptment = new HealthDept();
        healthDeptment.setPageSwitch(false);
        List<HealthDept> healthDeptmentList = healthDeptMapper.selectListByCondition(healthDeptment);
        mv.addObject("healthDeptList", healthDeptmentList);

        return mv;
    }

    @RequestMapping("permission/adminDoEdit")
    @ArchivesLog(operationDescription = "修改管理员")
    public ModelAndView adminDoEdit(HttpServletRequest request) {

        String adminId = request.getParameter("adminId");

        // 取得数据库的数据
        Admin admin = adminMapper.selectByPrimaryKey(Integer.valueOf(adminId));
        // 密码
        String adminPassword = request.getParameter("adminPassword");
        if (StringUtils.isNotEmpty(adminPassword)) {
            admin.setAdminPassword(DigestUtils.md5Hex(adminPassword));
        }
        // 权限组
        String adminGid = request.getParameter("adminGid");
        admin.setAdminGid(Short.valueOf(adminGid));

        // 体检部门ID
        String healthDeptId = request.getParameter("healthDeptId");
        if (StringUtils.isNotEmpty(healthDeptId)) {
            admin.setHealthDeptId(Integer.valueOf(request.getParameter("healthDeptId")));
        }

        // 以上没有设定的值都为数据库的值

        int i = adminMapper.updateByPrimaryKeySelective(admin);
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i > 0) {
            modelAndView.addObject("msg", "管理员修改成功");
        } else {
            modelAndView.addObject("msg", "管理员修改失败");
        }
        modelAndView.addObject("returnUrl", "setting/permission");
        return modelAndView;
    }

    /**
     *  管理员删除
     * @param request
     * @return
     */
    @RequestMapping("permission/adminDelete")
    @ArchivesLog(operationDescription = "删除管理员")
    public ModelAndView adminDelete(HttpServletRequest request) {
        String[] adminId = request.getParameterValues("adminId");
        int i = 0;
        for (String id : adminId) {
            i += adminMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == adminId.length) {
            modelAndView.addObject("msg", "管理员删除成功");
        } else {
            modelAndView.addObject("msg", "管理员删除失败");
        }
        modelAndView.addObject("returnUrl", "setting/permission");
        return modelAndView;
    }

    /**
     * 管理员重复CHECK
     * @param admin
     * @return
     */
    @RequestMapping("permission/checkAdminName")
    public  @ResponseBody Boolean checkAdminName(Admin admin) {
        if(adminMapper.selectByCondition(admin).size()>0){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 权限组管理
     * @param gAdmin
     * @return
     */
    @RequestMapping("permission/groupList")
    @AuthPassport
    public ModelAndView groupList(GAdmin gAdmin) {
        gAdmin.setResultList(gAdminMapper.selectByCondition(gAdmin));
        ModelAndView view = new ModelAndView("setting/permission/groupList");
        view.addObject("page",gAdmin);
        return view;
    }

    /**
     *  权限组新增
     * @return
     * @throws Exception
     */
    @RequestMapping("permission/groupToAdd")
    public ModelAndView groupToAdd() throws Exception {
        List grouList = menusMapper.selectByCondition(BeanUtils.objectToMap(new Menus()));
        ModelAndView view = new ModelAndView("setting/permission/groupadd","info",grouList);
        return view;
    }

    @RequestMapping("permission/groupDoAdd")
    @ArchivesLog(operationDescription = "新增权限组")
    public ModelAndView groupDoAdd(GAdmin gAdmin) {
        int i = gAdminMapper.insert(gAdmin);
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i > 0) {
            modelAndView.addObject("msg", "权限组新增成功");
        } else {
            modelAndView.addObject("msg", "权限组新增失败");
        }
        modelAndView.addObject("returnUrl", "setting/permission/groupList");
        return modelAndView;
    }

    /**
     *  权限组修改
     * @param gAdmin
     * @return
     * @throws Exception
     */
    @RequestMapping("permission/groupToEdit")
    public ModelAndView groupToEdit(GAdmin gAdmin) throws Exception {
        List grouList = menusMapper.selectByCondition(BeanUtils.objectToMap(new Menus()));
        ModelAndView view = new ModelAndView("setting/permission/groupedit","info",grouList);
        view.addObject("gadmin",gAdminMapper.selectByPrimaryKey(gAdmin.getGid()));
        return view;
    }

    @RequestMapping("permission/groupDoEdit")
    @ArchivesLog(operationDescription = "修改权限组")
    public ModelAndView groupDoEdit(GAdmin admin) {
        int i = gAdminMapper.updateByPrimaryKeySelective(admin);
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i > 0) {
            modelAndView.addObject("msg", "权限组修改成功");
        } else {
            modelAndView.addObject("msg", "权限组修改失败");
        }
        modelAndView.addObject("returnUrl", "setting/permission/groupList");
        return modelAndView;
    }

    /**
     *  权限组删除
     * @param request
     * @return
     */
    @RequestMapping("permission/groupDelete")
    @ArchivesLog(operationDescription = "删除权限组")
    public ModelAndView groupDelete(HttpServletRequest request) {
        String[] gId = request.getParameterValues("gid");
        int i = 0;

        // 权限组内是否还有用户
        List<Admin>  adminList = null;
        for (String id : gId) {
            Admin admin = new Admin();
            admin.setAdminGid(Short.parseShort(id));
            adminList = adminMapper.selectByCondition(admin);
            if (adminList != null && adminList.size() > 0) {
                break;
            }
        }

        ModelAndView modelAndView = new ModelAndView("msg");
        if (adminList != null && adminList.size() > 0) {
            modelAndView.addObject("msg", "权限组删除失败:要删除的权限组内不能有任何管理员");
            modelAndView.addObject("returnUrl", "setting/permission/groupList");
            return modelAndView;
        }

        // 权限组删除
        for (String id : gId) {
            i += gAdminMapper.deleteByPrimaryKey(Short.parseShort(id));
        }
        if (i ==  gId.length) {
            modelAndView.addObject("msg", "权限组删除成功");
        } else {
            modelAndView.addObject("msg", "权限组删除失败");
        }
        modelAndView.addObject("returnUrl", "setting/permission/groupList");
        return modelAndView;
    }

    /**
     *  权限组重名CHECK
     * @param admin
     * @return
     */
    @RequestMapping("permission/checkgAdminName")
    public @ResponseBody Boolean checkgAdminName(GAdmin admin) {
        List<GAdmin> gAdminList = gAdminMapper.selectByCondition(admin);
        if (gAdminList.size() == 0) {
            return true;
        }
        // 修改时
        if (gAdminList.size() == 1) {
            // 修改的当前记录的数据时
            if (gAdminList.get(0).getGid() == admin.getGid()) {
                return true;
            }
        }
        // 添加时 或  修改的其他记录的数据时
        return false;
    }

    /**
     * 操作日志
     * @param ids
     * @return
     * @throws Exception
     */
    @RequestMapping(value="adminlog/deleteAdminLogByIds")
    public ModelAndView deleteAdminLogByIds(String [] ids) throws Exception {
        ModelAndView modelAndView = new ModelAndView("msg");
        if(ids != null) {
            List nList = Arrays.asList(ids);
            int delCount = adminLogService.deleteByIds(nList);
            if (delCount ==  ids.length) {
                modelAndView.addObject("msg", "操作日志删除成功");
            } else {
                modelAndView.addObject("msg", "操作日志删除失败");
            }
        }
        modelAndView.addObject("returnUrl", "setting/adminlog");
        return modelAndView;
    }

    /**
     * 菜单管理
     * @param menus
     * @return
     */

    @RequestMapping("menu")
    @AuthPassport
    public ModelAndView menuList(MenusVo menus) throws Exception {
        menus.setResultList(menusMapper.selectByCondition(menus));
        ModelAndView view = new ModelAndView("setting/menu/menuList");
        view.addObject("page",menus);
        return view;
    }

    @RequestMapping("menu/menuadd")
    public ModelAndView menuadd() throws Exception {
        Menus menus = new Menus();
        menus.setParentid(0);
        ModelAndView view = new ModelAndView("setting/menu/menuadd","info",menusMapper.selectByCondition(BeanUtils.objectToMap(menus)));
        return view;
    }
    @RequestMapping("menu/menuedit")
    public ModelAndView menuedit(Integer id) {
        MenusVo menus = new MenusVo();
        menus.setParentid(0);
        ModelAndView view = new ModelAndView("setting/menu/menuedit","info",menusMapper.selectByCondition(menus));
        view.addObject("menu",menusMapper.selectByPrimaryKey(id));
        return view;
    }

    @RequestMapping("menu/menuadddo")
    public ModelAndView admineditdo(Menus menus) {
        menusMapper.insert(menus);
        ModelAndView view = new ModelAndView("redirect:/setting/menu");
        return view;
    }

    @RequestMapping("menu/menueditdo")
    public ModelAndView menueditdo(Menus menus) {
        menusMapper.updateByPrimaryKeySelective(menus);
        ModelAndView view = new ModelAndView("redirect:/setting/menu");
        return view;
    }

    @RequestMapping("menu/menurm")
    public ModelAndView adminrm(Menus menus) {
        menusMapper.deleteByPrimaryKey(menus.getId());
        ModelAndView view = new ModelAndView("redirect:/setting/menu");
        return view;
    }

    /**
     *  节日管理
     * @param festival
     * @return
     */
    @RequestMapping(value = "festival")
    public ModelAndView festivalList(Festival festival){
        ModelAndView res = new ModelAndView("setting/festival/list");
        festival.setResultList(festivalMapper.selectListByCondition(festival));
        res.addObject("page",festival);
        return res;
    }

    /**
     *  节日添加
     * @return
     */
    @RequestMapping(value = "festival/toAdd")
    public ModelAndView toAddFestival() {
        ModelAndView view = new ModelAndView("setting/festival/add");
        return view;
    }
    @RequestMapping(value = "festival/doAdd")
    @ArchivesLog(operationDescription = "新增节日")
    public ModelAndView doAddFestival(Festival festival, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        // 节日和日期重复CHECK的处理
        boolean isExist = false;
        List<Festival> festivalList = festivalMapper.selectListByCondition(new Festival());
        for (Festival festivalDB : festivalList) {
            if (festival.getfName().equals(festivalDB.getfName()) && festival.getfDate().equals(festivalDB.getfDate())) {
                isExist = true;
                break;
            }
        }
        if (isExist) {
            modelAndView.addObject("msg", "节日新增失败：新增后的节日和日期已经存在");
            // returnUrl不设定时，返回到新增页面
            return modelAndView;
        }

        MemberBase memberBase = (MemberBase)request.getSession().getAttribute("memInfo");
        festival.setCreaterId(memberBase.getUserId());
        festival.setCreateName(memberBase.getUserName());
        festival.setCreateTime(DateUtil.toTimeString(new Date()));
        int i = festivalMapper.insertSelective(festival);
        if (i > 0) {
            modelAndView.addObject("msg", "节日新增成功");
        } else {
            modelAndView.addObject("msg", "节日新增失败");
        }
        modelAndView.addObject("returnUrl", "setting/festival");
        return modelAndView;
    }

    /**
     * 节日修改
     * @param request
     * @return
     */
    @RequestMapping(value = "festival/toEdit")
    public ModelAndView toEditFestival(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("setting/festival/edit");
        Integer fId =  Integer.valueOf(request.getParameter("fId"));
        Festival festival = festivalMapper.selectByPrimaryKey(fId);
        view.addObject("festival", festival);
        return view;
    }

    @RequestMapping(value = "festival/doEdit")
    @ArchivesLog(operationDescription = "修改节日")
    public ModelAndView doEditFestival(Festival festival,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        // 节日和日期重复CHECK的处理
        boolean isExist = false;
        List<Festival> festivalList = festivalMapper.selectListByCondition(new Festival());
        for (Festival festivalDB : festivalList) {
            if (festival.getfId() != festivalDB.getfId()) {
                if (festival.getfName().equals(festivalDB.getfName()) && festival.getfDate().equals(festivalDB.getfDate())) {
                    isExist = true;
                    break;
                }
            }
        }
        if (isExist) {
            modelAndView.addObject("msg", "节日修改失败：修改后的节日和日期已经存在");
            // returnUrl不设定时，返回到修改页面
            return modelAndView;
        }

        // 没有重复时，更新数据库
        int i = festivalMapper.updateByPrimaryKeySelective(festival);
        if (i > 0) {
            modelAndView.addObject("msg", "节日修改成功");
        } else {
            modelAndView.addObject("msg", "节日修改失败");
        }
        modelAndView.addObject("returnUrl", "setting/festival");
        return modelAndView;
    }

    /**
     * 节日删除
     * @param request
     * @return
     */
    @RequestMapping(value = "festival/delete")
    @ArchivesLog(operationDescription = "删除节日")
    public ModelAndView deleteFestival(HttpServletRequest request) {
        String[] fId = request.getParameterValues("fId");
        int i = 0;
        for (String id : fId) {
            i += festivalService.deleteFandFR(Integer.valueOf(id));
        }

        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == fId.length) {
            modelAndView.addObject("msg", "节日删除成功");
        } else {
            modelAndView.addObject("msg", "节日删除失败");
        }
        modelAndView.addObject("returnUrl", "setting/festival");
        return modelAndView;
    }

    /**
     * 关系管理
     * @param relation
     * @return
     */
    @RequestMapping(value = "relation")
    public ModelAndView relationList(Relation relation) {
        ModelAndView view = new ModelAndView("setting/relation/list");
        relation.setResultList(relationMapper.selectListByCondition(relation));
        view.addObject("page", relation);
        return view;
    }

    /**
     * 关系添加
     * @return
     */
    @RequestMapping(value = "relation/toAdd")
    public ModelAndView toAddRelation() {
        ModelAndView view = new ModelAndView("setting/relation/add");
        return view;
    }

    @RequestMapping(value = "relation/doAdd")
    @ArchivesLog(operationDescription = "新增关系")
    public ModelAndView doAddRelation(Relation relation, HttpServletRequest request) {
        MemberBase memberBase = (MemberBase)request.getSession().getAttribute("memInfo");
        relation.setCreaterId(memberBase.getUserId());
        relation.setCreateName(memberBase.getUserName());
        relation.setCreateTime(DateUtil.toTimeString(new Date()));
        int i = relationMapper.insert(relation);

        ModelAndView modelAndView = new ModelAndView("msg");
        if (i > 0) {
            modelAndView.addObject("msg", "关系新增成功");
        } else {
            modelAndView.addObject("msg", "关系新增失败");
        }
        modelAndView.addObject("returnUrl", "setting/relation");
        return modelAndView;
    }

    /**
     * 关系修改
     * @param request
     * @return
     */
    @RequestMapping(value = "relation/toEdit")
    public ModelAndView toEditRelation(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("setting/relation/edit");
        Integer rId =  Integer.valueOf(request.getParameter("rId"));
        Relation relation = relationMapper.selectByPrimaryKey(rId);
        view.addObject("relation", relation);
        return view;
    }

    @RequestMapping(value = "relation/doEdit")
    @ArchivesLog(operationDescription = "修改关系")
    public ModelAndView doEditRelation(Relation relation,HttpServletRequest request) {
        int i = relationMapper.updateByPrimaryKeySelective(relation);
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i > 0) {
            modelAndView.addObject("msg", "关系修改成功");
        } else {
            modelAndView.addObject("msg", "关系修改失败");
        }
        modelAndView.addObject("returnUrl", "setting/relation");
        return modelAndView;
    }

    /**
     * 关系删除
     * @param request
     * @return
     */
    @RequestMapping(value = "relation/delete")
    @ArchivesLog(operationDescription = "删除关系")
    public ModelAndView deleterRlation(HttpServletRequest request) {
        String[] rId = request.getParameterValues("rId");
        int i = 0;
        for (String id : rId) {
            i += relationMapper.deleteByPrimaryKey(Integer.valueOf(id));
        }

        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == rId.length) {
            modelAndView.addObject("msg", "关系删除成功");
        } else {
            modelAndView.addObject("msg", "关系删除失败");
        }
        modelAndView.addObject("returnUrl", "setting/relation");
        return modelAndView;
    }

    /**
     * 关系名称重复CHECK
     * @param relation
     * @return
     */
    @RequestMapping("relation/checkRName")
    public @ResponseBody Boolean checkRName(Relation relation) {
        List<Relation> relationList = relationMapper.selectListByCondition(relation);
        if (relationList.size() == 0) {
            return true;
        }
        // 修改时
        if (relationList.size() == 1) {
            // 修改的当前记录的数据时
            if (relationList.get(0).getrId() == relation.getrId()) {
                return true;
            }
        }
        // 添加时 或  修改的其他记录的数据时
        return false;
    }

    /**
     *  参数设置
     * @param enumParam
     * @return
     */
    @RequestMapping(value = "enumParam")
    public ModelAndView enumParamList(EnumParam enumParam){
        ModelAndView res = new ModelAndView("setting/param/list");
        enumParam.setResultList(enumParamMapper.selectListByCondition(enumParam));
        res.addObject("page",enumParam);
        return res;
    }

    /**
     *  参数添加
     * @return
     */
    @RequestMapping(value = "enumParam/toAdd")
    public ModelAndView toAddEnumParam() {
        ModelAndView view = new ModelAndView("setting/param/add");
        return view;
    }
    @RequestMapping(value = "enumParam/doAdd")
    @ArchivesLog(operationDescription = "新增参数")
    public ModelAndView doAddEnumParam(EnumParam enumParam, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        // 参数类型和参数名称重复CHECK的处理
        boolean isExist = false;
        List<EnumParam> enumParamList = enumParamMapper.selectListByCondition(new EnumParam());
        for (EnumParam enumParamDB : enumParamList) {
            if (enumParam.getParamId() != enumParamDB.getParamId()) {
                if (enumParam.getParamType().equals(enumParamDB.getParamType()) && enumParam.getParamKey().equals(enumParamDB.getParamKey())) {
                    isExist = true;
                    break;
                }
            }
        }
        if (isExist) {
            modelAndView.addObject("msg", "参数新增失败：新增后的参数类型和参数名称已经存在");
            // returnUrl不设定时，返回到新增页面
            return modelAndView;
        }

        MemberBase memberBase = (MemberBase)request.getSession().getAttribute("memInfo");
        enumParam.setCreaterId(memberBase.getUserId());
        enumParam.setCreateName(memberBase.getUserName());
        enumParam.setCreateTime(DateUtil.toTimeString(new Date()));
        int i = enumParamMapper.insertSelective(enumParam);
        if (i > 0) {
            modelAndView.addObject("msg", "参数新增成功");
        } else {
            modelAndView.addObject("msg", "参数新增失败");
        }
        modelAndView.addObject("returnUrl", "setting/enumParam");
        return modelAndView;
    }

    /**
     * 参数修改
     * @param request
     * @return
     */
    @RequestMapping(value = "enumParam/toEdit")
    public ModelAndView toEditEnumParam(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("setting/param/edit");
        Integer paramId =  Integer.valueOf(request.getParameter("paramId"));
        EnumParam enumParam = enumParamMapper.selectByPrimaryKey(paramId);
        view.addObject("enumParam", enumParam);
        return view;
    }

    @RequestMapping(value = "enumParam/doEdit")
    @ArchivesLog(operationDescription = "修改参数")
    public ModelAndView doEditEnumParam(EnumParam enumParam,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("msg");
        // 参数类型和参数名称重复CHECK的处理
        boolean isExist = false;
        List<EnumParam> enumParamList = enumParamMapper.selectListByCondition(new EnumParam());
        for (EnumParam enumParamDB : enumParamList) {
            if (enumParam.getParamId() != enumParamDB.getParamId()) {
                if (enumParam.getParamType().equals(enumParamDB.getParamType()) && enumParam.getParamKey().equals(enumParamDB.getParamKey())) {
                    isExist = true;
                    break;
                }
            }
        }
        if (isExist) {
            modelAndView.addObject("msg", "参数修改失败：修改后的参数类型和参数名称已经存在");
            // returnUrl不设定时，返回到修改页面
            return modelAndView;
        }

        // 没有重复时，更新数据库
        int i = enumParamMapper.updateByPrimaryKeySelective(enumParam);
        if (i > 0) {
            modelAndView.addObject("msg", "参数修改成功");
        } else {
            modelAndView.addObject("msg", "参数修改失败");
        }
        modelAndView.addObject("returnUrl", "setting/enumParam");
        return modelAndView;
    }

    /**
     * 参数删除
     * @param request
     * @return
     */
    @RequestMapping(value = "enumParam/delete")
    @ArchivesLog(operationDescription = "删除参数")
    public ModelAndView deleteEnumParam(HttpServletRequest request) {
        String[] paramId = request.getParameterValues("paramId");
        int i = 0;
        for (String id : paramId) {
            i += enumParamMapper.deleteByPrimaryKey(Integer.valueOf(id));
        }

        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == paramId.length) {
            modelAndView.addObject("msg", "参数删除成功");
        } else {
            modelAndView.addObject("msg", "参数删除失败");
        }
        modelAndView.addObject("returnUrl", "setting/enumParam");
        return modelAndView;
    }
}
